from config_manager import (
    set_wifi_config,
    update_config_section,
    show_config,
    delete_config,
    load_config
)
import time

def setup_wifi():
    """
    Setup WiFi configuration interactively.
    """
    print("=== WiFi Configuration Setup ===")
    ssid = input("Enter WiFi SSID: ")
    password = input("Enter WiFi Password: ")
    
    if set_wifi_config(ssid, password):
        print("WiFi configuration saved successfully!")
        return True
    else:
        print("Failed to save WiFi configuration.")
        return False

def setup_ntp():
    """
    Setup NTP configuration.
    """
    print("=== NTP Configuration Setup ===")
    print("Current NTP servers configuration will be displayed first.")
    
    config = load_config()
    ntp_config = config.get('ntp', {})
    print(f"Current servers: {', '.join(ntp_config.get('servers', []))}")
    print(f"Current max retries: {ntp_config.get('max_retries', 2)}")
    print(f"Current retry interval: {ntp_config.get('retry_interval', 2)} seconds")
    
    print("\nEnter new NTP servers (comma-separated, press Enter to keep current):")
    servers_input = input("Servers: ")
    
    print("Enter max retries (press Enter to keep current):")
    retries_input = input("Max retries: ")
    
    print("Enter retry interval in seconds (press Enter to keep current):")
    interval_input = input("Retry interval: ")
    
    # Prepare new configuration
    new_config = {}
    
    if servers_input.strip():
        servers = [server.strip() for server in servers_input.split(',')]
        new_config['servers'] = servers
    
    if retries_input.strip():
        try:
            new_config['max_retries'] = int(retries_input)
        except ValueError:
            print("Invalid number for max retries, keeping current value.")
    
    if interval_input.strip():
        try:
            new_config['retry_interval'] = int(interval_input)
        except ValueError:
            print("Invalid number for retry interval, keeping current value.")
    
    if new_config:
        if update_config_section('ntp', new_config):
            print("NTP configuration updated successfully!")
            return True
        else:
            print("Failed to update NTP configuration.")
            return False
    else:
        print("No changes made to NTP configuration.")
        return True

def setup_timezone():
    """
    Setup timezone offset.
    """
    print("=== Timezone Setup ===")
    config = load_config()
    current_offset = config.get('settings', {}).get('timezone_offset', 8)
    print(f"Current timezone offset: UTC+{current_offset}")
    
    print("Enter new timezone offset (in hours from UTC, e.g., 8 for UTC+8):")
    offset_input = input("Offset: ")
    
    if offset_input.strip():
        try:
            new_offset = int(offset_input)
            if update_config_section('settings', {'timezone_offset': new_offset}):
                print(f"Timezone updated to UTC+{new_offset} successfully!")
                return True
            else:
                print("Failed to update timezone.")
                return False
        except ValueError:
            print("Invalid number for timezone offset.")
            return False
    else:
        print("No changes made to timezone.")
        return True

def run_config_wizard():
    """
    Run the configuration wizard.
    """
    while True:
        print("\n" + "="*40)
        print("ESP32C3 Configuration Manager")
        print("="*40)
        print("1. Setup WiFi")
        print("2. Setup NTP Servers")
        print("3. Setup Timezone")
        print("4. Show Current Configuration")
        print("5. Delete Configuration")
        print("6. Exit")
        print("="*40)
        
        choice = input("Enter your choice (1-6): ")
        
        if choice == '1':
            setup_wifi()
        elif choice == '2':
            setup_ntp()
        elif choice == '3':
            setup_timezone()
        elif choice == '4':
            show_config()
        elif choice == '5':
            confirm = input("Are you sure you want to delete the configuration? (y/n): ")
            if confirm.lower() == 'y':
                delete_config()
        elif choice == '6':
            print("Exiting configuration manager.")
            break
        else:
            print("Invalid choice. Please enter a number between 1 and 6.")
        
        # Add a short delay before showing the menu again
        print("\nPress Enter to continue...")
        input()

if __name__ == '__main__':
    print("ESP32C3 Configuration Setup Tool")
    print("This tool helps you configure WiFi, NTP, and other settings.")
    print("\nLoading current configuration...")
    time.sleep(1)
    run_config_wizard()